package phylacterium.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import phylacterium.beans.RegisterBean;
import phylacterium.entities.UserEntity;
import phylacterium.tools.DBException;
import phylacterium.tools.DBOperations;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	RegisterBean bean = null;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			ArrayList<String[]> genres = DBOperations.select("SELECT id,name FROM Genres ORDER BY 2 ASC");
			ArrayList<String[]> education = DBOperations.select("SELECT id,name FROM Education");
			if (bean == null)
				bean = new RegisterBean(genres, education);
			else {
				bean.genres = genres;
				bean.education = education;
			}

			request.setAttribute("bean", bean);

			bean = null;

			ServletContext ctx = this.getServletContext();
			RequestDispatcher dispatcher = ctx
					.getRequestDispatcher("/register.jsp");

			dispatcher.forward(request, response);

		} catch (DBException e) {
			DBException.lastError = e;
			response.sendRedirect("error");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UserEntity newUser = null;
		try {
			newUser = new UserEntity(request);
			
			//Check if login is filled
			if (request.getParameter("login").length() == 0){
				bean = new RegisterBean();
				bean.loginError = "Enter login";
				bean.user = newUser;
				response.sendRedirect("register");
				return;
			}
			
			//Check if passwords match
			if (request.getParameter("password").length() == 0){
				bean = new RegisterBean();
				bean.passwordError = "Enter password";
				bean.user = newUser;
				response.sendRedirect("register");
				return;
			} else if (!request.getParameter("password").equals(request.getParameter("confirmPassword"))){
				bean = new RegisterBean();
				bean.passwordError = "Passwords must match";
				bean.user = newUser;
				response.sendRedirect("register");
				return;
			} 
			
			//Check if age is OK
			if (newUser.ageField.length() > 0 && newUser.age == null){
				bean = new RegisterBean();
				bean.ageError = "Age must be a valid number";
				bean.user = newUser;
				response.sendRedirect("register");
				return;
			}
			
			DBOperations.createUser(newUser);
			HttpSession session = request.getSession();
			if (newUser.name != null)
				session.setAttribute("userName", newUser.name);
			else
				session.setAttribute("userName", newUser.login);
			session.setAttribute("userId", newUser.id);
			response.sendRedirect("homepage");
		} catch (DBException e) {
			if (e.getCode() == 1062) {
				bean = new RegisterBean();
				bean.loginError = "Login already taken";
				bean.user = newUser;
				response.sendRedirect("register");
			} else {
				DBException.lastError = e;
				response.sendRedirect("error");
			}
		}
	}

}
